package controllers

import (
	beego "github.com/beego/beego/v2/server/web"
	"medical/common"
	"medical/models"
	"time"
)

type UserController struct {
	beego.Controller
}

// 注册

func (c *UserController) Register() {
	username := c.GetString("username")
	password := c.GetString("password")

	user := models.User{
		Username: username,
		Password: common.Md5Password(password),
	}
	err := models.DB.Create(&user).Error
	if err != nil {
		c.Data["json"] = JsonRes{
			Code: 0,
			Msg:  "注册失败",
			Data: nil,
		}
		c.ServeJSON()
		return
	} else {
		c.Data["json"] = JsonRes{
			Code: 200,
			Msg:  "注册成功",
			Data: nil,
		}
		c.ServeJSON()
		return
	}

}

// 登录

func (c *UserController) Login() {
	username := c.GetString("username")
	password := c.GetString("password") //123456
	key := "lock-" + username
	count, _ := models.Rdb.Get(key).Int()
	if count >= 3 {
		c.Data["json"] = JsonRes{
			Code: 0,
			Msg:  "账号已经冻结，2小时重试，冻结剩余时间",
			Data: nil,
		}
		c.ServeJSON()
		return
	}
	var user models.User
	err := models.DB.Where("username = ? ", username).First(&user).Error
	if err != nil {
		c.Data["json"] = JsonRes{
			Code: 0,
			Msg:  "账号错误",
			Data: nil,
		}
		c.ServeJSON()
		return
	} else {
		if user.Password == common.Md5Password(password) {
			models.Rdb.Del(key) //登录成功删除缓存
			c.Data["json"] = JsonRes{
				Code: 200,
				Msg:  "登录成功",
				Data: nil,
			}
			c.ServeJSON()
		} else {
			// 秘密错误，次数+1 （计算器）
			models.Rdb.Incr(key)
			models.Rdb.Expire(key, time.Hour*2) //设置锁定时间
			c.Data["json"] = JsonRes{
				Code: 0,
				Msg:  "密码错误",
				Data: nil,
			}
			c.ServeJSON()
		}
	}
}
